package com.treetao.union.core.tencent.microapp;

import org.springframework.stereotype.Component;

import com.treetao.union.core.exception.DevMException;
import com.treetao.union.core.tencent.microapp.option.MicroappOption;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import me.chanjar.weixin.common.error.WxErrorException;

/**
 * 微信小程序用户相关服务
 * @author Dev.M
 *
 */
@Component
public class TencentMicroappUserService {
	WxMaService service = new WxMaServiceImpl();
	
	public void config(MicroappOption option) {
		if (option == null) {
			throw new DevMException("option required");
		}
		WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
		config.setAppid(option.getAppId());
		config.setSecret(option.getSecret());
		config.setMsgDataFormat("JSON");
		service.setWxMaConfig(config);
	}
	
	/**
	 * code换取sessionKey
	 * @param code
	 * @return
	 * @throws WxErrorException
	 */
	public WxMaJscode2SessionResult code2session(String code){
		try {
			return service.getUserService().getSessionInfo(code);
		} catch (WxErrorException e) {
			e.printStackTrace();
			throw new DevMException("code2session失败");
		}
	}
	
	/**
	 * 小程序登录
	 * @param sessionKey
	 * @param signature
	 * @param rawData
	 * @param encryptedData
	 * @param iv
	 * @return
	 */
	public WxMaUserInfo getUserInfo(String sessionKey,String signature, String rawData, String encryptedData, String iv) {
		// 用户信息校验
        if (!service.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            throw new DevMException("用户信息校验失败");
        }

        // 解密用户信息	
		return service.getUserService().getUserInfo(sessionKey, encryptedData, iv);
	}
	
	/**
	 * 获取用户绑定手机号信息
	 * @param sessionKey
	 * @param signature
	 * @param rawData
	 * @param encryptedData
	 * @param iv
	 * @return
	 */
    public WxMaPhoneNumberInfo getPhone(String sessionKey, String encryptedData, String iv) {
        // 解密
        return service.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);

    }
}
